<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span class="header-title">博客管理</span>
                <div class="extra">
                    <el-button type="primary" @click="clearArticleModel(); visibleDrawer = true; title = '添加博客';">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        添加博客
                    </el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline class="search-form">
            <el-form-item label="博客分类：">
                <el-select placeholder="请选择" v-model="categoryId" clearable>
                    <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="博客状态：">
                <el-select v-model="searchStatus" placeholder="请选择" clearable>
                    <el-option label="审核中" value="审核中"></el-option>
                    <el-option label="审核不通过" value="审核不通过"></el-option>
                    <!-- <el-option label="未发布" value="未发布"></el-option> -->
                    <el-option label="已发布" value="已发布"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="articleList">搜索</el-button>
                <el-button @click="categoryId = ''; searchStatus = ''; articleList();">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 博客列表 -->
        <el-table :data="articles" style="width: 100%; margin-top: 20px;" @row-click="handleRowClick" border stripe
            highlight-current-row class="article-table">
            <el-table-column label="博客标题" width="200" prop="title" show-overflow-tooltip></el-table-column>
            <el-table-column label="分类" prop="categoryName" width="100" align="center"></el-table-column>
            <el-table-column label="博客概要" prop="summary" min-width="200">
                <template #default="{ row }">
                    <span class="summary-text">{{ row.summary.replace(/<[^>]+>/g, '') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="发表时间" prop="createTime" width="180" align="center"></el-table-column>
            <el-table-column label="状态" prop="status" width="100" align="center"></el-table-column>
            <el-table-column label="操作" width="200" align="center">
                <template #default="{ row }">
                    <div class="action-icons">
                        <el-button :icon="Edit" circle plain type="primary" @click.stop="showDialog(row)" />
                        <el-button :icon="Delete" circle plain type="danger" @click.stop="deleteArticle(row)" />
                        <!-- <el-button v-if="row.status === '审核中'" :icon="Check" circle plain type="success" @click.stop="access(row)" />
                        <el-button v-if="row.status === '审核中'" :icon="Close" circle plain type="warning" @click.stop="unaccess(row)" /> -->
                    </div>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" class="pagination-bar" />
        <!-- 抽屉 -->
        <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
            <!-- 添加博客表单 -->
            <el-form :model="articleModel" label-width="100px" class="drawer-form">
                <el-form-item label="博客标题">
                    <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
                </el-form-item>
                <el-form-item label="博客分类">
                    <el-select placeholder="请选择" v-model="articleModel.categoryId">
                        <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="博客概要">
                    <div class="editor">
                        <quill-editor theme="snow" v-model:content="articleModel.summary" contentType="text" />
                    </div>
                </el-form-item>
                <el-form-item label="博客内容">
                    <div class="editor">
                        <quill-editor theme="snow" v-model:content="articleModel.content" contentType="html" />
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="title == '添加博客' ? addArticle() : updateArticle()">发布</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </el-card>
</template>

<script setup>
import {
    Edit,
    Delete,
    Check,
    Close,
    Plus
} from '@element-plus/icons-vue'

import { ref } from 'vue'
const lastPage = ref(1) // 用于记录上一次的页码
//博客分类数据模型
const categorys = ref([])

//用户搜索时选中的分类id
const categoryId = ref('')

//博客状态搜索
const searchStatus = ref('')

//博客列表数据模型
const articles = ref([
    {
        "id": 5,
        "title": "陕西旅游攻略",
        "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
        "summary": "游遍祖国大好河山",
        "categoryId": 2,
        "createTime": "2023-09-03 11:55:30",
        "updateTime": "2023-09-03 11:55:30"
    }
])

//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(3)//每页条数

// 获取全部分类
import { articleCategoryListAllService } from '@/api/article.js';
import useLastPageStore  from '@/stores/lastPage.js';
const lastPageStore = useLastPageStore();
const articleCategory = async () => {
    pageNum.value = lastPageStore.lastPage;
    let result = await articleCategoryListAllService();
    categorys.value = result.data;
    // pageNum.value = lastPage.value; // 恢复上一次的页码
}

articleCategory();

// 博客分页列表
import { articleListAllService } from '@/api/article.js';
const articleList = async () => {
    let statusNum;
    if (searchStatus.value === '审核中') {
        statusNum = 0;
    } else if (searchStatus.value === '审核不通过') {
        statusNum = 3;
    } else if (searchStatus.value === '未发布') {
        statusNum = 1;
    } else if (searchStatus.value === '已发布') {
        statusNum = 2;
    } else {
        statusNum = null; // 如果没有选择状态，则为null
    }
    let params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        categoryId: categoryId.value ? categoryId.value : null,
        status: statusNum
    }
    let result = await articleListAllService(params);
    total.value = result.data.total;
    articles.value = result.data.items;

    // 扩展categoryName属性
    for (let i = 0; i < articles.value.length; i++) {
        let article = articles.value[i]; // 获取第i篇博客
        // 对于第i篇博客，遍历博客分类列表，找到对应的博客分类名称
        for (let j = 0; j < categorys.value.length; j++) {
            if (article.categoryId == categorys.value[j].id) {
                article.categoryName = categorys.value[j].categoryName;
            }
        }
    }
    for (let i = 0; i < articles.value.length; i++) {
        let article = articles.value[i];
        // 将状态数字转换为字符串
        if (article.status === 0) {
            article.status = '审核中';
        } else if (article.status === 1) {
            article.status = '未发布';
        } else if (article.status === 2) {
            article.status = '已发布';
        } else if (article.status === 3) {
            article.status = '审核不通过';
        }
    }
}
articleList();
//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size;
    articleList();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num;
    articleList();
    // lastPage.value = num; // 记录当前页码
    lastPageStore.lastPage = num; // 使用 Pinia 存储当前页码
    // console.log(lastPage.value);
}


//控制抽屉是否显示
const visibleDrawer = ref(false)
//添加表单数据模型
const articleModel = ref({
    title: '',
    categoryId: '',
    content: '',
    summary: ''
})

// 使用富文本编辑器
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'

// 导入token
import { useTokenStore } from '@/stores/token.js';
const tokenStore = useTokenStore();
// 添加博客
import { articleAddService } from '@/api/article.js'
import { ElMessage } from 'element-plus';
const addArticle = async () => {
    // 调用接口实现博客的添加
    let result = await articleAddService(articleModel.value);
    ElMessage.success(result.message ? result.message : '添加成功！');
    clearArticleModel();
    // 消除抽屉
    visibleDrawer.value = false;
    // 刷新列表
    articleList();
}
const clearArticleModel = () => {
    articleModel.value = {
        title: '',
        categoryId: '',
        content: '',
        summary: ''
    }
}
// title，控制弹窗的标题
const title = ref('');
// 弹出窗口
const showDialog = (row) => {
    // 弹出窗口
    visibleDrawer.value = true;
    // 设置标题
    title.value = '编辑博客';
    // 拷贝数据
    articleModel.value.title = row.title;
    articleModel.value.categoryId = row.categoryId;
    articleModel.value.content = row.content;
    articleModel.value.summary = row.summary;
    // 扩展id
    articleModel.value.id = row.id;
}

// 调用接口，实现博客编辑
import { articleUpdateService } from '@/api/article.js';
const updateArticle = async () => {
    let result = await articleUpdateService(articleModel.value);
    ElMessage.success(result.message ? result.message : '修改成功！');
    // 消除弹窗
    visibleDrawer.value = false;
    // 刷新数据
    articleList();
}
// 删除博客
import { articleDeleteService } from '@/api/article.js';
import { ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router';
const deleteArticle = async (row) => {
    // 添加弹框
    ElMessageBox.confirm(
        '确认删除本条数据？',
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let result = await articleDeleteService(row.id);  // 调用api删除数据
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
            // 刷新列表
            articleList();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
const router = useRouter();
const handleRowClick = (row) => {
    router.push({
        path: `/article/detail/${row.id}`,
        // 传递参数
        query: {
            categoryName: encodeURIComponent(row.categoryName)
        }
    });
}
// const access = async (row) => {
//     // 调用接口，实现博客审核通过
//     await articleUpdateService({ ...row, status: 1 });
//     ElMessage.success('操作成功！');
//     await articleList(); // 刷新列表
// }
// const unaccess = async (row) => {
//     // 调用接口，实现博客审核不通过
//     await articleUpdateService({ ...row, status: 3 });
//     ElMessage.success('操作成功！');
//     await articleList(); // 刷新列表
// }
</script>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;
    background: #f7f8fa;
    border-radius: 12px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
    padding-bottom: 30px;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10px 0 0 0;

        .header-title {
            font-size: 22px;
            font-weight: 600;
            color: #222;
            letter-spacing: 1px;
        }

        .extra {
            display: flex;
            align-items: center;
        }
    }
}

.search-form {
    margin: 20px 0 0 0;

    .el-form-item {
        margin-right: 20px;
    }
}

.article-table {
    border-radius: 8px;
    overflow: hidden;
    background: #fff;

    .el-table__header th {
        background: #f2f3f5;
        color: #333;
        font-weight: 500;
    }

    .el-table__row {
        transition: background 0.2s;
    }

    .el-table__row:hover {
        background: #f5f7fa;
    }

    .summary-text {
        color: #666;
        font-size: 14px;
        word-break: break-all;
    }
    .action-icons {
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        gap: 10px;
        min-width: 160px;
    }
}

.pagination-bar {
    margin-top: 24px;
    display: flex;
    justify-content: flex-end;
}

.el-select {
    --el-select-width: 220px;
}

/* 抽屉样式 */
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.drawer-form {
    padding: 10px 0;

    .el-form-item {
        margin-bottom: 18px;
    }
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}
</style>